﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kokomo.Environment;
using System.Reflection;
using System.IO;
using System.Resources;
using System.Windows.Input;
using System.Collections;
using Kokomo.Environment.Services;

namespace Kokomo.PeInspector.Reflection
{
	[ViewType(typeof(AssemblyResourcesView))]
	class AssemblyResourcesViewModel : NotifierObject
	{
		public AssemblyResourcesViewModel(
			Assembly assembly,
			ICommand navigateToCommand
			)
		{
			if (assembly == null) throw new ArgumentNullException("assembly");

			this.NavigateToCommand = navigateToCommand;

			this.LoadResources(assembly);
			this._saveResourceCommand = new DelegatedCommand(this.SaveResource, this.CanSaveResource);
		}

		public IEnumerable<AssemblyResourceItem> ResourceItems { get; private set; }

		private AssemblyResourceItem _selectedResourceItem;
		public AssemblyResourceItem SelectedResourceItem { get { return this._selectedResourceItem; }
			set
			{
				this._selectedResourceItem = value;
				this.OnPropertyChanged("SelectedResourceItem");
				this._saveResourceCommand.OnCanExecuteChanged();
			}
		}
		public ICommand NavigateToCommand { get; private set; }

		private void LoadResources(Assembly assembly)
		{
			IEnumerable<AssemblyResource> resources = ResourceExtractor.ExtractResources(
				assembly,
				ResourceExtractionOptions.IncludePack
				);

			List<AssemblyResourceItem> resourceViewModels = new List<AssemblyResourceItem>();
			foreach (var resource in resources)
			{
				AssemblyResourceItem resourceViewModel = new AssemblyResourceItem(resource);
				resourceViewModels.Add(resourceViewModel);
				
			}

			this.ResourceItems = resourceViewModels;
		}

		private DelegatedCommand _saveResourceCommand;
		public ICommand SaveResourceCommand { get { return this._saveResourceCommand; } }
		private bool CanSaveResource()
		{
			return (this.SelectedResourceItem != null);
		}
		private void SaveResource()
		{
			if (this.SelectedResourceItem == null) return;
			AssemblyResource resource = this.SelectedResourceItem.Resource;

			string fileName = resource.Name;
			{
				int lastSlash = fileName.LastIndexOfAny(new char[] { '\\', '/' });
				if (lastSlash >= 0)
				{
					fileName = fileName.Substring(lastSlash + 1);
				}
			}

			fileName = EnvironmentServices.UiService.ShowSaveFileDialog(new FileDialogOptions()
			{
				Title = UiString.FromString(Messages.SaveResourceTitle),
				InitialFileName = fileName
			});
			if (fileName == null) return;

			byte[] resourceData = resource.GetResourceData();
			using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
			{
				stream.Write(resourceData, 0, resourceData.Length);
			}

			//this.Host.SaveResourceToFile(this.Assembly, this.SelectedResourceViewModel.Name);
		}
	}
}
